// by Xeno
#define THIS_FILE "fn_spawn_trench.sqf"
#include "x_setup.sqf"
private ["_pos", "_dir", "_trenchtype", "_trench"];

if (__pGetVar(GVAR(isinaction))) exitWith {
	GVAR(commandingMenuIniting) = false;
};

if ((player call FUNC(GetHeight)) > 5) exitWith {
	systemChat (localize "STR_DOM_MISSIONSTRING_241");
	GVAR(commandingMenuIniting) = false;
};

if (!isNull __pGetVar(GVAR(trench))) exitWith {
	systemChat (localize "STR_DOM_MISSIONSTRING_587");
	GVAR(commandingMenuIniting) = false;
};

_pos = player modeltoworld [0,1,0];
// TYRGHEN - putting the item a bit inside the ground to make it smaller
_pos set [2, -0.4];
_dir = direction player;

if (surfaceIsWater _pos) exitWith {
	systemChat (localize "STR_DOM_MISSIONSTRING_588");
	GVAR(commandingMenuIniting) = false;
};

if (isOnRoad _pos) exitWith {
	systemChat (localize "STR_DOM_MISSIONSTRING_589");
	GVAR(commandingMenuIniting) = false;
};

__pSetVar [QGVAR(isinaction), true];

systemChat (localize "STR_DOM_MISSIONSTRING_590");

// TYRGHEN - added a global variable
_trenchtype = GVAR(trench_type);

player playMove "AinvPknlMstpSlayWrflDnon_medic";
sleep 3;
waitUntil {animationState player != "AinvPknlMstpSlayWrflDnon_medic"};
GVAR(commandingMenuIniting) = false;
if (!alive player) exitWith {
	systemChat (localize "STR_DOM_MISSIONSTRING_591");
	__pSetVar [QGVAR(isinaction), false];
};

_trench = createVehicle [_trenchtype, _pos, [], 0, "NONE"];
_trench setdir _dir;
_trench setPos _pos;

[QGVAR(p_o_a2), [GVAR(string_player), _trench]] call FUNC(NetCallEventCTS);
__pSetVar [QGVAR(trench), _trench];
__pSetVar [QGVAR(isinaction), false];

waituntil { sleep 12.3456; (_trench distance player) > 200 || (!alive player) };
if (!isnull _trench) then {
	[QGVAR(p_o_a2r), [GVAR(string_player), _trench]] call FUNC(NetCallEventCTS);
	deleteVehicle _trench;
};
if (alive player) then {
	__pSetVar [QGVAR(trench), objNull];
};